<template>
  <div class="relatime">
    <div class="relatime-top">
      <div class="top">
        <el-checkbox
          v-model="checked1"
          label="A侧"
          size="large"
          @change="changeQuery"
        />
        <el-checkbox
          v-model="checked2"
          label="B侧"
          size="large"
          @change="changeQuery"
        />
      </div>
      <div class="center">
        <div class="charts-box" ref="chartBox1"></div>
      </div>
    </div>
    <div class="relatime-bottom">
      <div class="top">
        <p>实时数据</p>
      </div>
      <div class="center">
        <el-row>
          <el-col :span="6" v-for="(item, key) in dataList" :key="key">
            <el-row v-if="item.name != ''">
              <el-col :span="3"></el-col>
              <el-col :span="18">
                <div class="item">
                  <div class="name">
                    <p>{{ item.name }}:</p>
                  </div>
                  <div class="value">
                    <p>{{ item.value }}</p>
                  </div>
                  <div class="dw">
                    <p>{{ item.dw }}</p>
                  </div>
                </div>
              </el-col>
              <el-col :span="3"></el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import { nextTick } from "vue";
import { relatimeInit, relatimeCurve } from "../http/api";
import { getDate } from "../utils/index";
import { ElMessage } from "element-plus";
const data = reactive({
  checked1: true,
  checked2: false,
  dataList: [
    {
      id: 1,
      name: "A侧实侧氧量",
      value: 120,
      dw: "%",
      bg: "yellow",
      key: "oxygenA_real",
    },
    {
      id: 2,
      name: "B侧实侧氧量",
      value: 120,
      dw: "%",
      bg: "yellow",
      key: "oxygenB_real",
    },
    {
      id: 3,
      name: "机组负荷",
      value: 120,
      dw: "MW",
      key: "unitLoad",
    },
    {
      id: 4,
      name: "A磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowA",
    },
    {
      id: 5,
      name: "A侧预侧氧量",
      value: 120,
      dw: "%",
      bg: "hong",
      key: "oxygenA_predict",
    },
    {
      id: 6,
      name: "B侧预侧氧量",
      value: 120,
      dw: "%",
      bg: "hong",
      key: "oxygenB_predict",
    },
    {
      id: 7,
      name: "主汽压力",
      value: 120,
      dw: "Mpa",
      key: "mainSteamPressure",
    },
    {
      id: 8,
      name: "B磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowB",
    },
    {
      id: 9,
      name: "A侧融合氧量",
      value: 120,
      dw: "%",
      bg: "lv",
      key: "oxygenA_merge",
    },
    {
      id: 10,
      name: "B侧融合氧量",
      value: 120,
      dw: "%",
      bg: "lv",
      key: "oxygenB_merge",
    },
    {
      id: 11,
      name: "主汽温度",
      value: 120,
      dw: "℃",
      key: "mainSteamTemperature",
    },
    {
      id: 12,
      name: "C磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowC",
    },
    {
      id: 13,
      name: "A侧一次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowA_primary",
    },
    {
      id: 14,
      name: "B侧一次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowB_primary",
    },
    {
      id: 15,
      name: "炉膛负压",
      value: 120,
      dw: "Pa",
      key: "furnace_pressure",
    },
    {
      id: 16,
      name: "D磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowD",
    },
    {
      id: 17,
      name: "A侧二次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowA_secondary",
    },
    {
      id: 18,
      name: "B侧二次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowB_secondary",
    },
    {
      id: 19,
      name: "一次总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_primary",
    },
    {
      id: 20,
      name: "E磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowE",
    },
    {
      id: 21,
      name: "A侧一次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureA_primary",
    },
    {
      id: 22,
      name: "B侧一次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureB_primary",
    },
    {
      id: 23,
      name: "二次总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_secondary",
    },
    {
      id: 24,
      name: "F磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowF",
    },
    {
      id: 25,
      name: "A侧二次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureA_secondary",
    },
    {
      id: 26,
      name: "B侧二次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureB_secondary",
    },
    {
      id: 27,
      name: "炉膛总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_total",
    },
    {
      id: 28,
      name: "",
      value: "",
      dw: "",
      key: "",
    },
    {
      id: 29,
      name: "A侧实测CO量",
      value: 120,
      dw: "ppm",
      key: "COA_real",
    },
    {
      id: 30,
      name: "B侧实测CO量",
      value: 120,
      dw: "ppm",
      key: "COB_real",
    },
  ],
  datePicker: "",
  checked1List: [
    {
      key: "oxygenA_merge",
      label: "A侧融合氧量",
    },
    {
      key: "oxygenA_predict",
      label: "A侧预侧氧量",
    },
    {
      key: "oxygenA_real",
      label: "A侧实侧氧量",
    },
  ],
  checked2List: [
    {
      key: "oxygenB_merge",
      label: "B侧融合氧量",
    },
    {
      key: "oxygenB_predict",
      label: "B侧预侧氧量",
    },
    {
      key: "oxygenB_real",
      label: "B侧实侧氧量",
    },
  ],
  xyList: {
    xData: [],
    yData: [],
    legend: [],
  },
  source: null,
  newCheckedList: [],
});
const {
  checked1,
  checked2,
  dataList,
  datePicker,
  checked1List,
  checked2List,
  xyList,
  source,
  newCheckedList,
} = toRefs(data);
const chartBox1 = ref(null);
let chartOne = undefined;
async function relatimeCurveFn() {
  return await relatimeCurve().then((res) => {
    const groupedByNames = res.reduce((acc, item) => {
      if (!acc[item.name]) {
        acc[item.name] = [];
      }
      acc[item.name].push(item);
      return acc;
    }, {});
    let xData = [];
    let yData = [];
    let legend = [];
    let valueList =
      newCheckedList.value.length > 0
        ? newCheckedList.value
        : checked1List.value;
    valueList.map((item, index) => {
      let yDataParam = [];
      legend.push(item.label);
      groupedByNames[item.key].map((child, childIndex) => {
        if (index == 0) {
          xData.push(child.timestamp);
        }
        yDataParam.push(child.value);
      });
      let param = {
        name: item.label,
        label: item.key,
        type: "line",
        smooth: true, // 平滑曲线
        showSymbol: false,
        data: yDataParam,
      };
      yData.push(param);
    });

    return {
      xData,
      yData,
      legend,
    };
  });
}
function initChart() {
  drawChart();
}
async function changeQuery() {
  newCheckedList.value = [];
  if (checked1.value == true && checked2.value == false) {
    newCheckedList.value = checked1List.value;
  }
  if (checked1.value == false && checked2.value == true) {
    newCheckedList.value = checked2List.value;
  }
  if (checked1.value == true && checked2.value == true) {
    newCheckedList.value = checked1List.value.concat(checked2List.value);
  }
  if (checked1.value == false && checked2.value == false) {
    checked1.value = true;
    newCheckedList.value = checked1List.value;
    ElMessage({
      type: "error",
      message: "至少选择一侧",
    });
  }

  if (chartOne) {
    // chartOne.clear();
    xyList.value = await relatimeCurveFn();
    drawChart();
  }
}
async function drawChart() {
  if (!chartOne) {
    chartOne = echarts.init(chartBox1.value, "macarons");
  }
  xyList.value = await relatimeCurveFn();
  let option = {
    legend: {
      show: true,
      top: 15,
      textStyle: { color: "#ffffff" },
      data: xyList.value.legend,
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
      axisPointer: {
        animation: false,
      },
      cofine: true,
    },
    grid: {
      top: 50,
      left: 30,
      right: 30,
      bottom: 40,
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: xyList.value.xData,
      axisLine: { lineStyle: { color: "#ccc" } },
      axisTick: { length: 3 },
      axisLabel: { color: "#999" },
    },
    yAxis: {
      name: "氧量/%",
      type: "value",
      axisLine: { show: true, lineStyle: { color: "#ccc" } },
      axisLabel: { color: "#999" },
      splitLine: { show: false },
    },
    series: xyList.value.yData,
    animationDuration: 0,
    animationEasing: "cubicInOut",
  };
  chartOne.setOption(option, true);
  //   chartOne.on("click", (param) => {
  //     chartOneClick(param);
  //   });
}
function getFormatTime(stamp) {
  // stamp = stamp * 1000;
  let data = stamp ? new Date(stamp) : new Date();
  let year = data.getFullYear();
  let month = data.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let date = data.getDate();
  date = date < 10 ? "0" + date : date;
  return (
    year +
    "-" +
    month +
    "-" +
    date +
    " " +
    new Date(stamp).toLocaleTimeString("chinese", { hour12: false })
  );
}

//数据初始化
function ininData() {
  relatimeInit().then((res) => {
    dataList.value.map((item) => {
      item.value = Number(res[item.key]).toFixed(2);
    });
  });
}
onMounted(() => {
  setTimeout(function () {
    longLink();
  }, 1000);
});
onActivated(() => {
  ininData();
  initChart();
});
function timeCha(arr) {
  let first = arr[0];
  let last = arr[arr.length - 1];
  if (new Date(last).getTime() - new Date(first).getTime() > 5 * 60 * 1000) {
    for (let i = 0; i < arr.length; i++) {
      let first = arr[i];
      if (
        new Date(last).getTime() - new Date(first).getTime() >
        5 * 60 * 1000
      ) {
        arr.shift();
        xyList.value.yData.map((item) => {
          item.data.shift();
        });
        //  xyList.value.yData.shift();
        i--;
      } else {
        break;
      }
    }
  }
}
function longLink() {
  if (window.EventSource) {
    source.value = new EventSource(
      "http://121.41.120.212:8080/api/oxygen/realtime"
    );

    source.value.onopen = function (event) {};
    source.value.addEventListener(
      "realtime_data",
      (event) => {
        let data = eval("(" + event.data + ")");
        let time = getDate(data.timestamp * 1000);
        let dateTime = time.date + " " + time.time;

        xyList.value.xData.push(dateTime);
        xyList.value.yData.map((item) => {
          item.data.push(Number(data[item.label]).toFixed(2));
        });
        dataList.value.map((item) => {
          item.value = Number(data[item.key]).toFixed(2);
        });
        timeCha(xyList.value.xData);

        if (chartOne && chartOne.getOption().series.length > 0) {
          nextTick(() => {
            chartOne.setOption({
              xAxis: {
                data: xyList.value.xData,
              },
              series: xyList.value.yData,
              legend: {
                data: xyList.value.legend,
              },
            });
          });
        }
      },
      false
    );

    // Jane
    source.value.addEventListener(
      "alarm",
      (event) => {
        // let data = eval("(" + event.data + ")");
        // store.alarmList = data && data.length > 0 ? data : [];
      },
      false
    );

    source.value.onerror = function (event) {
      source.value.close();
      longLink();
    };
  }
}
//initChart();
</script>
<style lang="scss">
.relatime {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  .relatime-top,
  .relatime-bottom {
    width: 100%;
    height: 49%;
    border: 1px solid #319efd;
    background: url(../assets/img/kuang.png) center center no-repeat;
    background-size: cover;
  }
  .relatime-top {
    .top {
      width: 100%;
      height: 5.3vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .center {
      width: 100%;
      height: calc(100% - 5.3vh);
      .charts-box {
        width: 100%;
        height: 100%;
      }
    }
  }
  .relatime-bottom {
    padding: 9px;
    .top {
      width: 21vw;
      height: 4.7vh;
      position: relative;
      background: url(../assets/img/title-bt.png) center center no-repeat;
      background-size: cover;
      display: flex;
      justify-content: flex-start;
      p {
        font-family: Source Han Sans CN;
        font-weight: bold;
        margin-left: 30px;
        font-size: 22px;
        color: #daedff;
        line-height: 27px;
        background: linear-gradient(
          0deg,
          #79c5ff 0%,
          #ffffff 59.8388671875%,
          #ffffff 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    .center {
      width: 100%;
      height: calc(100% - 5.3vh);
      .el-row {
        height: 100%;
        .item {
          height: 100%;
          display: flex;
          align-items: center;
          .name {
            width: 120px;
            min-height: 27px;
            background: url(../assets/img/key-lan.png) center center no-repeat;
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #011750;
            }
          }
          .name.hong {
            background: url(../assets/img/key-hong.png) center center no-repeat;
            background-size: cover;
          }
          .name.lv {
            background: url(../assets/img/key-lv.png) center center no-repeat;
            background-size: cover;
          }
          .name.yellow {
            background: url(../assets/img/key-huang.png) center center no-repeat;
            background-size: cover;
          }
          .value {
            width: 5.3vw;
            border: 1px solid;
            border-image: linear-gradient(0deg, #02b0fe, #72fbf6) 10 10;
            min-height: 27px;
            // background: url(../assets/img/value-lan.png) center center no-repeat;
            // background-size: cover;

            display: flex;
            justify-content: center;
            align-items: center;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #16bdfd;
              line-height: 25px;
            }
          }
          .value.hong {
            border: 1px solid;
            border-image: linear-gradient(0deg, #ff7877, #ffdfd3) 10 10;
            p {
              color: #ff7878;
            }
          }
          .value.lv {
            border: 1px solid;
            border-image: linear-gradient(0deg, #56dd6f, #cdffd6) 10 10;
            p {
              color: #48eb67;
            }
          }
          .value.yellow {
            border: 1px solid;
            border-image: linear-gradient(0deg, #dcb51b, #fdf3cf) 10 10;
            p {
              color: #ffd633;
            }
          }
          .dw {
            width: 40px;
            margin: 3px;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #16bdfd;
            }
          }
          .dw.hong {
            p {
              color: #ff7878;
            }
          }
          .dw.lv {
            p {
              color: #48eb67;
            }
          }
          .dw.yellow {
            p {
              color: #ffd633;
            }
          }
        }
      }
    }
  }
}
</style>
